package org.firecloud.h5fun.controller.service;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.CommonConfig;
import org.firecloud.h5fun.model.CommonFunction;
import org.firecloud.h5fun.model.CommonQuery;
import org.firecloud.h5fun.model.CommonQueryInfoError;
import org.firecloud.h5fun.model.javabean.UserBean;
import org.json.JSONObject;
/**
 * 登陆通过Ajax方法调用URL：ajax_login<br>
 * 必须登陆：false<br>
 * 必须管理：false<br>
 * 参数：<br>
 * mail，必须，登陆用户的邮箱<br>
 * password，必须，登陆用户的密码<br>
 * vcode，必须，图片中的验证码{@link GetVerificationCode}
 * 注：无<br>
 * @author fc
 */
public class AjaxLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONObject json = new JSONObject();
		Connection conn = null;
		try {
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			CommonConfig config = (CommonConfig) req.getServletContext().getAttribute("commonConfig");
			String mail = req.getParameter("mail");
			String password = req.getParameter("password");
			if (CommonFunction.check_mail(mail) && CommonFunction.check_password(password)) {
				if (CommonFunction.check_vcode(req, "vcode")) {
					conn = config.getConn();
					UserBean loginUser = CommonQuery.select_login(conn, mail, password);
					CommonQuery.update_user_last_login_time(conn,loginUser.getId());
					req.getSession().setAttribute("loginUser",loginUser);
					json.put("type", 0);
					json.put("name", loginUser.getName());
				} else {
					json.put("type", -1);
					json.put("msg", "验证码错误");
				}
			} else {
				json.put("type", -3);
				json.put("msg", "帐号密码格式错误");
			}
		} catch (CommonQueryInfoError e) {
			json.put("type", -2);
			json.put("msg", "帐号或密码错误");
		} catch (Exception e) {
			json.put("type", -4);
			json.put("msg", "未知错误");
			Logger.getRootLogger().error(e);
		}finally {
			if(conn!=null){
				try {
					conn.close();
				} catch (Exception e) {
					Logger.getRootLogger().error(e);
				}
			}
		}
		req.getSession().setAttribute("vcode", null);
		resp.getWriter().print(json);
	}
}
